package com.example.li_han.servlet;

import com.example.li_han.pojo.News;
import com.example.li_han.service.NewsService;
import com.google.gson.Gson;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取置顶新闻Servlet
 */
@WebServlet(name = "GetTopNews", value = "/GetTopNews")
public class GetTopNews extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应类型和字符编码
        response.setContentType("application/json;charset=utf-8");

        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 1. 调用业务逻辑，查询置顶新闻
            NewsService newsService = new NewsService();
            List<News> topNewsList = newsService.getTopNews();

            // 2. 构建响应数据
            resultMap.put("code", 200);
            resultMap.put("msg", "查询成功");
            resultMap.put("count", topNewsList.size());
            resultMap.put("data", topNewsList);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "查询置顶新闻失败: " + e.getMessage());
        }

        // 3. 返回JSON数据
        Gson gson = new Gson();
        String json = gson.toJson(resultMap);
        response.getWriter().write(json);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        doGet(req, resp); // POST请求也调用doGet方法
    }
}